package com.sl.transport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sl.transport.common.exception.SLException;
import com.sl.transport.domain.OrganDTO;
import com.sl.transport.enums.ExceptionEnum;
import com.sl.transport.repository.OrganRepository;
import com.sl.transport.service.OrganService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrganServiceImpl implements OrganService {

    @Resource
    private OrganRepository organRepository;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 无需指定type，根据id查询
     *
     * @param bid 机构id
     * @return 机构信息
     */
    @Override
    public OrganDTO findByBid(Long bid) {
        OrganDTO organDTO = organRepository.findByBid(bid);
        if (ObjectUtil.isNotEmpty(organDTO)) {
            return organDTO;
        }
        throw new SLException(ExceptionEnum.ORGAN_NOT_FOUND);
    }

    /**
     * 无需指定type，根据ids查询
     *
     * @param bids 机构ids
     * @return 机构信息
     */
    @Override
    public List<OrganDTO> findByBids(List<Long> bids) {
        List<OrganDTO> organDTOList = organRepository.findByBids(bids);
        if (CollUtil.isNotEmpty(organDTOList)) {
            return organDTOList;
        }
        throw new SLException(ExceptionEnum.ORGAN_NOT_FOUND);
    }

    /**
     * 查询所有的机构，如果name不为空的按照name模糊查询
     *
     * @param name 机构名称
     * @return 机构列表
     */
    @Override
    public List<OrganDTO> findAll(String name) {
        List<OrganDTO> organDTOList = organRepository.findAll(name);
        if (CollUtil.isNotEmpty(organDTOList)) {
            return organDTOList;
        }
        throw new SLException(ExceptionEnum.ORGAN_NOT_FOUND);
    }

    /**
     * 查询机构树
     *
     * @return 机构树
     */
    @Override
    public String findAllTree() {
        // 1. 查询机构信息
        List<OrganDTO> organDTOList = this.findAll(null);
        if (CollUtil.isEmpty(organDTOList)) {
            return "";
        }
        // 2. 封装树状结构
        List<Tree<Long>> treeList = TreeUtil.build(organDTOList, 0L, ((organDTO, tree) -> {
            tree.setId(organDTO.getId());
            tree.setParentId(organDTO.getParentId());
            //把其他属性转化为map存进tree
            tree.putAll(BeanUtil.beanToMap(organDTO));
            //忽略bid，因为tree.id就是bid，重复了
            tree.remove("bid");
        }));
        // 3. 返回json字符串
        try {
            return this.objectMapper.writeValueAsString(treeList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new SLException(ExceptionEnum.ORGAN_TYPE_ERROR);
        }
    }

}
